﻿using AuthCenter.Api.Write.Application.Command.Role;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using AutoMapper;
using MediatR;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace AuthCenter.Api.Write.Application.Hander.Role
{
    public class UpdateRoleHander : IRequestHandler<UpdateRoleCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> _roleRepository;
        private readonly IBaseRepository<UserRoleModel> _userRoleRepository;
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IMapper _mapper;
        public UpdateRoleHander(IBaseRepository<RoleModel> roleRepository, IMapper mapper, IBaseRepository<UserRoleModel> userRoleRepository, IBaseRepository<UserModel> userRepository)
        {
            _roleRepository = roleRepository;
            _mapper = mapper;
            _userRoleRepository = userRoleRepository;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 编辑角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var user = _roleRepository.GetAll().Where(x => x.RoleName == request .RoleName && x.IsDeleted == false && x.Id != request.Id).FirstOrDefault();
            if (user != null)
            {
                res.Code = ApiEnums.Error;
                res.Message = "角色已存在";
            }
            var model = _mapper.Map<RoleModel>(request);
            model.UpdateUserName = "张三";
            model.UpdateTime = DateTime.Now;
            model.CreateUserName = "李四";
            model.CreateTime = DateTime.Now;
            int i=_roleRepository.Update(model);
            if (i > 0) 
            {
                res.Code = ApiEnums.OK;
                res.Message = "编辑成功";
               res.Data = i;
            }
            else
            {
                res.Code = ApiEnums.Fail;
                res.Message = "编辑失败";
            }
            return Task.FromResult(res);
        }
    }
}
